﻿using Microsoft.AspNetCore.Http.Features;
using SH.Common.CommonReturn;
using SH.Common.Helper;
using SH.Multitenant.Application.IServices.IUser;
using SH.Multitenant.Domain.Multitenant;
using SH.Multitenant.Infrastructure.IRepository;
using SQLitePCL;
using System;
using System.Collections.Generic;
using System.IO.Pipes;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace SH.Multitenant.Application.Services
{
    public class UserServices : BaseServices<User>, IUserServices
    {
        private readonly IUserRepository _userRepository;
        private readonly JwtTokenHelper _jwtHelper;
        public UserServices(IUserRepository repository, JwtTokenHelper jwtHelper) : base(repository)
        {
            _userRepository = repository;
            _jwtHelper = jwtHelper;
        }
        //租户登录
        public async Task<ApiResult<LoginResponseDTO>> UserLogin(LoginRequestDTO request)
        {
            ApiResult<LoginResponseDTO> apiResult = new ApiResult<LoginResponseDTO>();
            LoginResponseDTO response = new LoginResponseDTO();
            //if (request == null)
            //{
            //    apiResult.Error(ApiResult<LoginResponseDTO>.ErrorType.Request, "用户名密码不能为空");
            //}
            var user = await _userRepository.GetModelByConditionAsync(x => x.UName == request.UName);
            //用户名不存在
            if (user == null)
            {
                apiResult.Error(ApiResult<LoginResponseDTO>.ErrorType.Request, "用户名不存在");
            }
            //账号已锁定
            else if (user.ErrorTimes == 3)
            {
                apiResult.Error(ApiResult<LoginResponseDTO>.ErrorType.Service, $"该用户已锁定，解锁时间为：{user.LockTime!.Value.AddHours(1)}");
            }
            //账号密码不匹配
            else if (user.UPwd != request.UPwd)
            {
                user.ErrorTimes += 1;
                if (user.ErrorTimes == 3)
                {
                    user.LockTime = DateTime.Now;
                    apiResult.Error(ApiResult<LoginResponseDTO>.ErrorType.Service, $"登录次数超过限制，账号已被锁定！解锁时间为：{user.LockTime!.Value.AddHours(1)}");
                }
                apiResult.Error(ApiResult<LoginResponseDTO>.ErrorType.Request, $"账号密码不匹配，您还剩余{3 - user.ErrorTimes}次输入机会");
            }
            //登录成功
            else
            {
                user.ErrorTimes = 0;
                var token = _jwtHelper.CreateJwtToken(user, user.TenantId);
                response.UId = user.UId.ToString();
                response.UName = user.UName;
                response.TenantId = user.TenantId;
                response.Token = token;
                response.IsTenant = true;
                apiResult.Success(response);
            }
            return apiResult;
        }


    }
}
